<template>
  <j-modal title="1688匹配关系" :width="1200" :visible.sync="modalVisible" :maskClosable="false">
    <a-spin :spinning="submitLoading">
      <a-form-model ref="form" :model="formData" :rules="rules">
        <a-form-model-item label="采购链接" prop="url" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-search v-model="formData.url" placeholder="请输入1688采购链接" @search="parseLink">
            <a-button slot="enterButton" :loading="parseLoading">解析</a-button>
          </a-input-search>
        </a-form-model-item>
        <a-form-model-item label="供应商名称" prop="name" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-model="formData.name" placeholder="请输入1688采购链接并解析" :disabled="true"> </a-input>
          <div v-show="showNothingHint" class="nothing-hint">
            此供应商在系统中不存在，保存成功后将自动添加到供应商库。
          </div>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol">
          <template #label> <span style="color: red;">*</span>入库规格 : 供应商规格 </template>
          <div class="specs-box">
            <a-form-model-item prop="specsMy">
              <a-input-number
                v-model="formData.specsMy"
                placeholder="入库规格"
                :min="1"
                :max="999999"
                :step="1"
                :precision="0"
              >
              </a-input-number>
            </a-form-model-item>
            <div class="split-ico">:</div>
            <a-form-model-item prop="specsSup">
              <a-input-number
                v-model="formData.specsSup"
                placeholder="供应商规格"
                :min="1"
                :max="999999"
                :step="1"
                :precision="0"
              >
              </a-input-number>
            </a-form-model-item>
            <a-tooltip placement="right">
              <template slot="title">
                <div>入库规格：2 则表示入库的时候是按照2/组作为 1 个入库。</div>
                <div>供应商规格：10则表示采购的时候是按照10/组作为 1 个采购。</div>
              </template>
              <a-icon type="info-circle" class="circle-ico" />
            </a-tooltip>
          </div>
        </a-form-model-item>
        <div v-if="formData.productInfo" class="product-info-box">
          <a-divider orientation="left"> 1688商品 </a-divider>
          <div>
            <a-checkbox v-model="formData.checkMultiple" @change="changeRadio">我要匹配多属性</a-checkbox>
            <a-tooltip placement="right">
              <template slot="title">
                <div>勾选后，下方1688商品可每个属性可选择多属性值，后续下单也会选择下单多属性值。</div>
              </template>
              <a-icon type="info-circle" class="circle-ico" />
            </a-tooltip>
          </div>
          <div class="product-info">
            <viewer :images="formData.productInfo.productImage.images">
              <img
                v-for="(i, index) in formData.productInfo.productImage.images"
                :key="index"
                :src="i"
                v-show="index == 0"
                class="product-image"
              />
            </viewer>
            <div class="product-content">
              <div class="product-name">商品名称：{{ formData.productInfo.subject }}</div>
              <a-form-model-item
                v-for="(item, index) in formData.attrList"
                :key="item.attributeID"
                :label="item.attributeName"
                :labelCol="{
                  xs: { span: 24 },
                  sm: { span: 4 },
                }"
                :wrapperCol="wrapperCol"
                style="margin-bottom: 10px"
                :prop="'attrList.' + index + '.checkVal'"
                :rules="{
                  required: true,
                  message: `请至少选择一个${item.attributeName}`,
                  trigger: 'change',
                }"
              >
                <a-checkbox-group v-if="formData.checkMultiple" v-model="item.checkVal">
                  <a-checkbox
                    v-for="item2 in item.valList"
                    :key="item2.attributeValue"
                    :value="item2.attributeValue"
                    class="check-item"
                  >
                    <img v-if="item2.skuImageUrl" :src="item2.skuImageUrl" class="sku-imgs" />
                    {{ item2.attributeValue }}
                  </a-checkbox>
                </a-checkbox-group>
                <a-radio-group v-else v-model="item.checkVal">
                  <a-radio
                    v-for="item2 in item.valList"
                    :key="item2.attributeValue"
                    :value="item2.attributeValue"
                    class="check-item"
                  >
                    <img v-if="item2.skuImageUrl" :src="item2.skuImageUrl" class="sku-imgs" />
                    {{ item2.attributeValue }}
                  </a-radio>
                </a-radio-group>
              </a-form-model-item>
            </div>
          </div>
        </div>
      </a-form-model>
    </a-spin>
    <template #footer>
      <a-button @click="modalVisible = false"> 取消 </a-button>
      <a-button type="primary" :loading="submitLoading" @click="handleOk"> 保存 </a-button>
    </template>
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'

export default {
  props: {
    // 是否显示弹框
    visible: {
      type: Boolean,
      default: false,
    },
    //
    defaultLink: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      modalVisible: this.visible,
      showNothingHint: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      formData: {
        id: '',
        url: this.defaultLink,
        name: '',
        specsMy: undefined,
        specsSup: undefined,
        checkMultiple: false,
        productInfo: undefined,
        attrList: [],
      },
      rules: {
        url: { required: true, message: '请输入采购链接!' },
        name: { required: true, message: '请输入1688采购链接并解析!' },
        specsMy: { required: true, message: '请输入入库规格!' },
        specsSup: { required: true, message: '请输入供应商规格!' },
      },
      url: {
        parseLink: '/purchase/auth/account/info1688',
        addSupplier: '/hzkj-product/product/productLibrary/supplier/add',
        querySupplierByName: '/hzkj-product/product/productLibrary/supplier/getByName',
      },
      parseLoading: false,
      submitLoading: false,
      skuList: [], // 保存查到的完整sku列表，用于选中对应属性后查询相应的sku信息
    }
  },
  watch: {
    modalVisible(val) {
      this.$emit('update:visible', val)
    },
  },
  methods: {
    // 解析1688链接
    parseLink() {
      this.$refs.form.validateField('url', (errorMessage) => {
        if (!errorMessage) {
          // 校验通过后请求解析链接
          this.parseLoading = true
          this.submitLoading = true
          getAction(this.url.parseLink, {
            url: this.formData.url,
          })
            .then(async (res) => {
              if (!res.success) {
                this.$message.warning(res.message)
                return
              }
              if (res.result.success) {
                const productInfo = res.result.productInfo
                let isBlack = await this.querySupplierHas(
                  `${productInfo.supplierLoginId}(${productInfo.sellerLoginId})`
                )
                if (isBlack) {
                  // 供应商在黑名单中，并且点击取消添加
                  return
                }

                this.formData.name = `${productInfo.supplierLoginId}(${productInfo.sellerLoginId})`
                this.formData.productInfo = productInfo
                this.skuList = (productInfo.productSkuInfos || []).map((i) => ({
                  ...i,
                  attributes: i.attributes.filter((i2) => i2.attrType != '1'), //这种类型的属性会导致匹配不对，展示也不对，过滤掉
                })) //保存查到的完整sku列表用于后期使用
                const attrList = []
                // 序列化产品属性用于展示渲染
                this.skuList.forEach((i1) => {
                  i1.attributes.forEach((i2) => {
                    const findItem = attrList.find((i3) => i3.attributeID == i2.attributeID)
                    if (findItem) {
                      if (!findItem.valList.some((i4) => i4.attributeValue == i2.attributeValue)) {
                        findItem.valList.push(i2)
                      }
                    } else {
                      attrList.push({
                        attributeID: i2.attributeID,
                        attributeName: i2.attributeName,
                        valList: [i2],
                      })
                    }
                  })
                })
                this.formData.attrList = attrList
              } else {
                this.$message.warning(res.result.errorMsg)
              }
            })
            .finally(() => {
              this.parseLoading = false
              this.submitLoading = false
            })
        }
      })
    },
    // 查询供应商是否存在，没有的话保存的时候要调用新增供应商接口
    querySupplierHas(name) {
      return new Promise((resolve) => {
        getAction(this.url.querySupplierByName, {
          name,
        }).then((res) => {
          if (res.success) {
            if (res.result) {
              this.showNothingHint = false
              if (res.result.supplierStatus == 1) {
                // 在黑名单中，需要提示
                this.$confirm({
                  content: (h) => {
                    return h(
                      'div',
                      {
                        domProps: {
                          innerHTML: `<div style="padding-left: 40px;"><span style="font-weight: bold;">您选择的供应商当前处于黑名单中</span>，还要继续添加吗？</div>`,
                        },
                      },
                      []
                    )
                  },
                  onOk: () => {
                    resolve()
                  },
                  onCancel: () => {
                    // 点了取消添加
                    resolve(true)
                  },
                })
              } else {
                // 不在在黑名单中
                this.formData.id = res.result.id
                resolve()
              }
            } else {
              // 不在供应商列表中中
              this.showNothingHint = true
              resolve()
            }
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    addSupplier() {
      return new Promise((resolve) => {
        this.submitLoading = true
        postAction(this.url.addSupplier, {
          name: this.formData.name,
          paymentMethod: '1',
          buyer: this.$store.getters.userInfo.username,
        })
          .then((res) => {
            if (res.success) {
              this.formData.id = res.result.id
              resolve()
            } else {
              this.$message.error(res.message)
            }
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    changeRadio() {
      this.formData.attrList = this.formData.attrList.map((i) => ({
        ...i,
        checkVal: undefined,
      }))
    },
    // 提交
    handleOk() {
      // 如果供应商不存在，先保存供应商，再添加供应商
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.showNothingHint) {
            await this.addSupplier()
          }

          // 根据选择的数据找出所有的skuId
          const specIds = []
          this.skuList.forEach((skuItem) => {
            let isInCheck = true // 判断当前的sku是否在选中的sku中(如果当前sku的所有属性都在选中的数据中，才表示该sku被选中)
            skuItem.attributes.forEach((skuAttr) => {
              const valItem = this.formData.attrList.find((formAttr) => skuAttr.attributeID == formAttr.attributeID) // 找到表单中对应的属性item
              if (this.formData.checkMultiple) {
                // 如果当前是多选则查询选中的数组中是否存在目标sku
                if (!valItem.checkVal.some((i) => i == skuAttr.attributeValue)) {
                  // 找不到，说明该sku没有被选中
                  isInCheck = false
                }
              } else if (valItem.checkVal != skuAttr.attributeValue) {
                // 如果当前是多选则查询选中的选项是否是目标sku
                isInCheck = false
              }
            })
            if (isInCheck) {
              specIds.push(skuItem.specId)
            }
          })
          console.log('specIds',specIds);
          this.$emit('submit', {
            ...this.formData,
            specId: specIds.join(','),
            attrList: this.formData.attrList.map((i) => ({
              attributeID: i.attributeID,
              attributeName: i.attributeName,
              checkVal: Array.isArray(i.checkVal) ? i.checkVal : [i.checkVal],
            })),
          })
          this.modalVisible = false
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.nothing-hint {
  font-size: 12px;
  color: #e36508;
  line-height: 1;
}
.specs-box {
  display: flex;
  /deep/ .ant-form-item {
    margin-bottom: 0;
  }

  .split-ico {
    margin: 5px;
    font-weight: bold;
  }

  .circle-ico {
    margin: 10px 0 0 10px;
  }
}
.product-info-box {
  padding: 0 50px;
}
.product-info {
  display: flex;
  margin-top: 20px;
}
.product-image {
  width: 100px;
  height: 100px;
  border-radius: 5px;
  cursor: pointer;
}
.product-content {
  margin-left: 20px;
}
.product-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.check-item {
  margin: 0 10px 10px 0;
  border: 1px solid #d9d9d9;
  padding: 5px;

  .sku-imgs {
    width: 50px;
    height: 50px;
  }
}
</style>
